﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using bdnt_pets_system_Entity;
using System.Windows.Data;
using bdnt_pets_system.Resources;

namespace bdnt_pets_system.PageViews.DataManager
{
    public partial class NewPartWindow : BaseWindow
    {
        DataServiceReference.DataServiceClient dClient;

        #region binding
        void BingData()
        {
            tbPartNo.SetBinding(TextBox.TextProperty, new Binding("PartNo")
            {
                Mode = BindingMode.TwoWay,
                NotifyOnValidationError = true,
                ValidatesOnExceptions = true
            });

            tbPartName.SetBinding(TextBox.TextProperty, new Binding("PartName")
            {
                Mode = BindingMode.TwoWay,
                NotifyOnValidationError = true,
                ValidatesOnExceptions = true
            });

            tbEnPartName.SetBinding(TextBox.TextProperty, new Binding("en_PartName")
            {
                Mode = BindingMode.TwoWay,
                NotifyOnValidationError = true,
                ValidatesOnExceptions = true
            });

            tbColor.SetBinding(TextBox.TextProperty, new Binding("PartColor")
            {
                Mode = BindingMode.TwoWay
            });
            tbRemark.SetBinding(TextBox.TextProperty, new Binding("Remark")
            {
                Mode = BindingMode.TwoWay
            });

            tbMaterialCode.SetBinding(TextBox.TextProperty, new Binding("MaterialCode")
            {
                Mode = BindingMode.TwoWay
            });

            tbWeight.SetBinding(TextBox.TextProperty, new Binding("Weight")
            {
                Mode = BindingMode.TwoWay
            });

            tbSupplier.SetBinding(TextBox.TextProperty, new Binding("Supplier")
            {
                Mode = BindingMode.TwoWay
            });

            tbFunctionGroup.SetBinding(TextBox.TextProperty, new Binding("FuncitionGroup")
            {
                Mode = BindingMode.TwoWay
            });


        }         
        void BindgExpression()
        {
            tbPartNo.GetBindingExpression(TextBox.TextProperty).UpdateSource();
            tbPartName.GetBindingExpression(TextBox.TextProperty).UpdateSource();
            tbEnPartName.GetBindingExpression(TextBox.TextProperty).UpdateSource();
        }
        #endregion

        public NewPartWindow(Tbl_Part cuObj)
        {
            InitializeComponent();
            CuTbl_Part = cuObj;
            InitData();
            BingData();
            dClient = new DataServiceReference.DataServiceClient(); 
            InitEvnet();
        }
        
        public Tbl_Part CuTbl_Part
        {
            get { return this.DataContext as Tbl_Part; }
            set { this.DataContext = value; }
        }

        void InitData()
        {
            if (CuTbl_Part.IsImportant)
                rbS.IsChecked = true;
            else rbF.IsChecked = true;
        }

        void InitEvnet()
        {
            btnCancel.Click += new RoutedEventHandler(btnCancel_Click);
            btnOk.Click += new RoutedEventHandler(btnOk_Click);
            dClient.SavePartCompleted += new EventHandler<DataServiceReference.SavePartCompletedEventArgs>(dClient_SavePartCompleted);
            DataServiceReference.DataServiceClient dataClient = new DataServiceReference.DataServiceClient();
            dataClient.GetAllStationListCompleted += new EventHandler<DataServiceReference.GetAllStationListCompletedEventArgs>(dataClient_GetAllStationListCompleted);
            dataClient.GetAllStationListAsync();
            dataClient.CloseAsync();
        }

        void dClient_SavePartCompleted(object sender, DataServiceReference.SavePartCompletedEventArgs e)
        {
            if (e.Result)
                this.DialogResult = true;
            else errorMsg.Text =MyStrings.bcsb+"!";
        }
        
        void dataClient_GetAllStationListCompleted(object sender, DataServiceReference.GetAllStationListCompletedEventArgs e)
        {
            var re = e.Result;
            gdStations.Children.Clear();
            if (re != null)
            {
                List<int> ls = !string.IsNullOrEmpty(CuTbl_Part.StationIds) ? CuTbl_Part.StationIds.Split(',').Select(p => Int32.Parse(p)).ToList() : new List<int>();
                int rowIndex = 0;
                var shops = re.Select(p => p.ShopId).Distinct();
                foreach (var item in shops)
                {
                    var sN = re.FirstOrDefault(p => p.ShopId == item).ShopName;
                    gdStations.RowDefinitions.Add(new RowDefinition());
                    CheckBox ck = new CheckBox()
                    {
                        Margin = new Thickness(0, 0, 5, 10),
                        Content = sN
                    };
                    ck.Checked += new RoutedEventHandler(ck_Checked);
                    ck.Unchecked += new RoutedEventHandler(ck_Checked);
                    Grid.SetRow(ck, rowIndex);
                    Grid.SetColumn(ck, 0);
                    gdStations.Children.Add(ck);

                    WrapPanel wp = new WrapPanel() { Margin = new Thickness(0, 0, 0, 10) };
                    Grid.SetRow(wp, rowIndex);
                    Grid.SetColumn(wp, 1);
                    ck.Tag = wp;

                    bool isVisble = false;
                    var stations = re.Where(p => p.ShopId == item).ToList();
                    stations.Where(p => !string.IsNullOrEmpty(p.StationName)).ToList().ForEach(p =>
                    {
                        CheckBox ck1 = new CheckBox()
                        {
                            Margin = new Thickness(0, 0, 5, 0),
                            Content = p.StationName,
                            Tag = p.Id
                        };
                        if (ls.Contains(p.Id))
                        {
                            ck.IsChecked = ck1.IsChecked = true;
                            isVisble = true;
                        }
                        wp.Children.Add(ck1);
                    });

                    gdStations.Children.Add(wp);
                    wp.Visibility = isVisble == true ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
                    rowIndex++;
                }
            }
        }
          
        void ck_Checked(object sender, RoutedEventArgs e)
        {
            var cuObj = (sender as CheckBox);
            var cuWp = cuObj.Tag as WrapPanel;
            if (cuObj.IsChecked == true)
                cuWp.Visibility = System.Windows.Visibility.Visible;
            else
            {
                cuWp.Visibility = System.Windows.Visibility.Collapsed;
                foreach (var item in cuWp.Children)
                {
                    (item as CheckBox).IsChecked = false;
                }
            }
        }         
        
        void btnOk_Click(object sender, RoutedEventArgs e)
        {
            BindgExpression();
            if (vs.Errors.Count > 0)
            {
                errorMsg.Text =MyStrings.sjtxbq;
                return;
            }
            
            List<int> stationIds = new List<int>();
            foreach (var item in gdStations.Children)
            {
                var cuk = item as CheckBox;
                if (cuk != null)
                {
                    var cuwp = (cuk.Tag as WrapPanel);
                    foreach (var ck in cuwp.Children)
                    {
                        var cuSelectCk = ck as CheckBox;
                        if (cuSelectCk.IsChecked.Value)
                            stationIds.Add(Int32.Parse(cuSelectCk.Tag.ToString()));
                    }
                }
            }
            CuTbl_Part.IsImportant = rbS.IsChecked.Value;       
            CuTbl_Part.StationIds = string.Join(",", stationIds);
            dClient.SavePartAsync(CuTbl_Part); 
        }

        void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

    }
}

